import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import Vue from 'vue';
const that = Vue.prototype;

export default class UrlRequest {
  constructor (validateResponse) {
    this.validateResponse = validateResponse;
  }
  async defaultRequest (options) {
    const { url, type, data = {}, isFormData, isExport, target, openLoading, closeLoading } = options;
    let loadingInstance = null;
    target ? loadingInstance = that.$loading({ target }) : openLoading(); // 启用loading
    try {
      const requestMethod = isExport ? ApiRequestExportTable : ApiRequest;
      const res = await requestMethod(url, type, data, isFormData);
      target ? loadingInstance.close() : closeLoading(); // 停用loading
      if (isExport) return res; // 导出请求不需要判断请求状态
      if (this.validateResponse(res)) return res; // 返回请求的response
    } catch (err) {
      target ? loadingInstance.close() : closeLoading(); // 停用loading
    }
  }
  async request (options, startLoading = () => {}, stopLoading = () => {}) {
    const { loadingFn } = options;
    const openLoading = loadingFn ? () => { loadingFn(true); } : startLoading; // 兼容处理两种loading传入方式
    const closeLoading = loadingFn ? () => { loadingFn(false); } : stopLoading; // 兼容处理两种loading传入方式
    const res = await this.defaultRequest({ ...options, openLoading, closeLoading });
    return res;
  }
  async get (options) {
    return this.request({ ...options, type: 'get' });
  }
  post (options) {
    return this.request({ ...options, type: 'post' });
  }
  export (options) {
    return this.request({ ...options, type: 'post', isExport: true });
  }
}
